package com.cx.base.day19_thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * countdownlatch是一个支持并发的计数器，可以被多个线程执行countdown()，即减-操作，直到0
 *
 * @Author: robert.song
 * @Date: Created in 2021/11/27
 */
@Slf4j
public class Thread_15_1_CountdownLatch {
    public static void main(String[] args) {
        CountDownLatch countdownLatch = new CountDownLatch(2);
//        子线程启动，并在结束时完成计数减一
        ExecutorService service = Executors.newFixedThreadPool(4);
//        等待，直到其它线程结束
        service.submit(() -> {
            try {
                log.info("waitting...");
                countdownLatch.await();
                log.info(Thread.currentThread().getState().toString());
                log.info(String.valueOf(countdownLatch.getCount()));
                log.info("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
//        其它三个线程执行
        service.submit(() -> {
            try {
                log.info("begin");
                log.info(String.valueOf(countdownLatch.getCount()));
                Thread.sleep(10000);
                countdownLatch.countDown();
                log.info(String.valueOf(countdownLatch.getCount()));

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        service.submit(() -> {
            try {
                log.info("begin");
                log.info(String.valueOf(countdownLatch.getCount()));
                Thread.sleep(10000);
                countdownLatch.countDown();
                log.info(String.valueOf(countdownLatch.getCount()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        service.submit(() -> {
            try {
                log.info("begin");
                log.info(String.valueOf(countdownLatch.getCount()));
                Thread.sleep(10000);
                countdownLatch.countDown();
                log.info(String.valueOf(countdownLatch.getCount()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


    }

}
